<script setup>
import { useCandidateStore } from '@/stores'
import { ref } from 'vue'
import { candidateUploadAvatarService } from '@/api/candidate'
import { Plus, Upload } from '@element-plus/icons-vue'

const uploadRef = ref()
const loading = ref(false)

const candidateStore = useCandidateStore()
const imgUrl = ref(candidateStore.candidate.avator)

/*选择预览图片*/
const onUploadFile = (file) => {
  const reader = new FileReader() //读取文件为Base64编码的字符串
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}

/*调用接口*/
const onUpdateAvatar = async () => {
  loading.value = true
  const data = {
    username: candidateStore.candidate.username,
    avator: imgUrl.value
  }
  await candidateUploadAvatarService({ candidate: data })
  await candidateStore.getCandidate()
  loading.value = false
  ElMessage.success('头像修改成功')
}
</script>

<template>
  <!-- 头像 -->
  <div
    class="box"
    v-loading="loading"
    element-loading-background="rgba(141,164,195, 0.4)"
  >
    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="onUploadFile"
    >
      <div class="avatar-box">
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <img v-else src="@/assets/img/avatar.jpg" width="200" class="avatar" />
      </div>
    </el-upload>
    <el-divider />
    <div class="but-box">
      <el-button
        @click="uploadRef.$el.querySelector('input').click()"
        :icon="Plus"
        color="#626aef"
        :dark="isDark"
        round
        >预览
      </el-button>
      <el-button
        @click="onUpdateAvatar"
        :icon="Upload"
        color="#626aef"
        :dark="isDark"
        round
        >上传
      </el-button>
    </div>
  </div>
</template>
<style scoped>
.avatar-uploader {
  :deep() {
    position: relative;
    top: +10px;
    left: +10px;
    .avatar-box {
      height: 150px;
      width: 150px;
    }
    .avatar {
      height: 150px;
      width: 150px;
      border-radius: 50%;
    }
  }
}
.but-box {
  position: relative;
  left: +20px;
  width: 280px;
  .el-button {
    position: relative;
    margin: 0 10px;
  }
}
.box {
  width: 400px;
  height: 250px;
  margin: 0 0 0 20px;
  border: 1px solid rgb(228, 219, 219);
}
</style>
